package com.zhanghe.security.provider;

import com.zhanghe.security.authenticationtoken.GithubAuthenticationToken;
import com.zhanghe.security.excepiton.LoginException;
import com.zhanghe.security.property.SecurityProperties;
import com.zhanghe.security.service.SimpleUserDetailsService;
import com.zhanghe.security.util.auth2.Oauth2Token;
import com.zhanghe.security.util.auth2.github.GithubAuthUtil;
import com.zhanghe.security.util.auth2.github.GithubUserInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;

import java.util.ArrayList;
import java.util.HashMap;

public class GithubAuthenticationProvider implements AuthenticationProvider {

    protected static final Logger logger = LoggerFactory.getLogger(GithubAuthenticationProvider.class);

    @Autowired
    private SecurityProperties securityProperties;

    @Autowired
    private SimpleUserDetailsService simpleUserDetailsService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        GithubAuthenticationToken auth = (GithubAuthenticationToken) authentication;
        String code = auth.getCode();
        Oauth2Token auth_token = GithubAuthUtil.getOauth2Token(code);
        GithubUserInfo userInfo = GithubAuthUtil.getGithubUserInfo(auth_token.getAccess_token());
        UserDetails userDetails = simpleUserDetailsService.loadUserByGithubId(userInfo.getId());
        if(userDetails==null){
            throw new LoginException("用户不存在");
        }
        Authentication res = new GithubAuthenticationToken(userDetails.getAuthorities(),String.valueOf(userInfo.getId()),userDetails.getUsername());
        return res;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return aClass.equals(GithubAuthenticationToken.class);
    }
}
